<template>
  <div class="rule-box">
    <div v-if="$route.query.type" class="back-title">
      <i class="el-icon-arrow-left" @click="$router.go(-1)">返回</i>
    </div>
    <div class="container">
      <div class="container-body">
        <div class="container-list">
          <hk-form
            ref="formRef"
            label-width="140"
            label-position="left"
            :is-disabled="isDisabled"
            :form-labels="formObj.formLabels"
            :rules="formObj.formRules"
            :data="formDatas"
            :dict-list="formObj.dictList"
            :btn-hidden="true"
            @handleEvent="handleEvent"
            @submit.native.prevent
          />
        </div>
        <!-- <div class="container-list">
        <el-descriptions title="基础信息" :column="2" border>
          <el-descriptions-item
            label="发起人"
            label-class-name="my-label"
            content-class-name="my-content"
          >
            {{ detailsData.sponsor }}
          </el-descriptions-item>
          <el-descriptions-item label="团队">{{
            detailsData.team
          }}</el-descriptions-item>
          <el-descriptions-item label="组织">
            <el-tag size="small">{{ detailsData.organ }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div> -->
        <div v-if="isShowForm" class="container-list">
          <div class="title">表单信息</div>
          <div class="form-list">
            <fm-generate-form
              ref="generateForm"
              :data="jsonData"
              :value="formAttr"
              :remote="remoteFuncs"
            />
            <el-upload
              v-if="isfileUpload==true"
              class="upload-demo"
              :action="fileOpts.url"
              :limit="fileOpts.limit"
              :headers="fileOpts.headers"
              :on-change="handleFileUploadProgress"
              multiple
              :file-list="fileList"
              :on-exceed="handleExceed"
              :on-error="handleError"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              accept=".zip,.docx,.xlsx"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" style="margin-top:20px;font-size:14px;"><span>支持扩展名：{{ fileOpts.accept }}</span></div>
            </el-upload>
          </div>
        </div>
      </div>

      <div v-if="!isDisabled" class="container-footer">
        <el-button @click="handleSubmit('saveDraft')">保存草稿</el-button>
        <el-button :disabled="!formDatas.flowId" @click="handleFlowView">查看流程</el-button>
        <el-button type="primary" @click="handleShowRemark">提交</el-button>
      </div>
      <remark-dialog
        ref="remarkDialogRef"
        @handleSubmit="handleSaveRemark"
      />
    </div>
  </div>
</template>
<script>
import HkForm from '@/components/HkForm'
import remarkDialog from './remarkDialog.vue'
import {
  listAllFlow,
  getFormVariables,
  saveWork,
  saveDraft,
  getById,
  getDraft,
  getNextNodeInfo
} from '@/api/workbench/workbenchList.js'
import { get, post } from '@/utils/request'
import { setJsonLists, isfileUpload } from '@/views/basicConfig/serviceConfig/utils/setArr.js'
import { getToken } from '@/utils/auth'
import axios from 'axios'

const BASE_URL = window.baseUrl.ticket
export default {
  components: { HkForm, remarkDialog },
  beforeRouteLeave(to, from, next) {
    from.meta.keepAlive = false
    next()
  },
  props: {
    title: {
      type: String,
      default() {
        return '新建'
      }
    }
  },
  data() {
    return {
      open: false,
      isDisabled: false,
      formDatas: {},
      formData: {},
      formObj: {
        formLabels: [
          {
            label: '服务',
            field: 'flowId',
            type: 'select',
            list: 'flowIdsLists',
            span: 24
          },
          { label: '标题', field: 'orderTitle', type: 'input', span: 24 }
        ],
        formRules: {
          flowId: [{ required: true, message: '请选择服务', target: 'change' }],
          orderTitle: [
            { required: true, message: '请输入标题', target: 'blur' }
          ]
        },
        dictList: {
          flowIdsLists: []
        }
      },
      allFlowMapLists: [],
      detailsList: [
        { label: '发起人', field: 'sponsor', span: 12 },
        { label: '团队', field: 'team', span: 12 },
        { label: '组织', field: 'organ', span: 24, type: 'slot' }
      ],
      detailsData: { sponsor: 'admin', team: '1111', organ: 'baolande' },
      jsonData: null,
      formAttr: null,
      comment: '',
      assignUserMap: {},
      serviceId: null,
      remoteFuncs: {},
      remoteObjs: [],
      isShowForm: false,
      isfileUpload: false,
      fileList: [],
      fileOpts: {
        url: window.baseUrl.ticket + '/attachment/upload',
        limit: 3,
        accept: 'zip,docx,xlsx',
        params: 'files',
        headers: { Authorization: 'Bearer ' + getToken() }
      },
      fileInfo: []
    }
  },
  async mounted() {
    await this.getListAllFlowMap()
    if (this.$route.query.id) {
      if (this.$route.query.type == 'copy') {
        const res = await getById({ id: this.$route.query.id })
        this.serviceId = res.serviceId
        this.formDatas = {
          flowId: res.flowId,
          orderTitle: res.orderTitle
        }
        this.fileInfo = JSON.parse(res.formData).attachmen
        this.jsonData = await this.getForm(res.flowId)
      } else {
        const res = await getDraft({ id: this.$route.query.id })
        this.serviceId = res.serviceId
        if (this.$route.query.type == 'view') {
          this.isDisabled = true
        }
        this.formDatas = {
          flowId: res.flowId,
          orderTitle: res.orderTitle
        }
        this.jsonData = await this.getForm(res.flowId)
        this.formAttr = JSON.parse(res.formData)
      }
    }
  },
  methods: {
    //  设置动态获取的form表单
    async setRemoteFunc(param) {
      const _self = this
      const newArr = await setJsonLists(param)
      //  判断是否有上传附件
      this.isfileUpload = await isfileUpload(newArr)
      newArr.forEach(i => {
        if (i.type == 'cascader' || i.type == 'radio' || i.type == 'select' || i.type == 'checkbox') {
          this.remoteObjs.push({ remoteFunc: i.options.remoteFunc, props: i.options.props })
        }
      })
      this.remoteObjs.forEach(i => {
        this.remoteFuncs[i.remoteFunc] = function(resolve) {
          const reg = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/g
          const reg2 = /^\//g
          if (/^post\(.*\)$/.test(i.remoteFunc)) {
            const match = /^post\('(.*)'(?:,'\{.*\}')?\)$/.exec(i.remoteFunc)
            if (match) {
              const url = match[1]
              const param = match.length > 1 ? match[2] : {}
              post(url, param).then(res => {
                resolve(res)
              })
            }
          } else if (reg.test(i.remoteFunc)) {
            get(i.remoteFunc).then(res => {
              resolve(res)
            })
          } else if (reg2.test(i.remoteFunc)) {
            get(BASE_URL + i.remoteFunc).then(res => {
              resolve(res)
            })
          } else {
            _self.$message.error('请配置正确的远端方法')
          }
        }
      })
    },
    // 获取流程列表
    getListAllFlowMap() {
      return new Promise((resolve) => {
        listAllFlow().then((res) => {
          //  流程下拉框
          this.formObj.dictList.flowIdsLists = res.map((i, index) => {
            return { label: i.serviceName, value: i.id, serviceId: i.serviceId, disabled: i.isSystem == true }
          })
          resolve()
        })
      })
    },
    //  获取表单
    getForm(query) {
      return new Promise((resolve) => {
        getFormVariables(query).then(async(res) => {
          this.jsonData = JSON.parse(res.formTemplate)
          this.formAttr = JSON.parse(res.formAttr)
          if (this.jsonData && this.jsonData?.list) {
            await this.setRemoteFunc(this.jsonData.list)
            this.isShowForm = true
          }
          resolve(this.jsonData)
        })
      })
    },
    //  触发表单变化
    async handleEvent(obj) {
      if (obj.field == 'flowId') {
        await this.getForm(obj.value)
        this.formObj.dictList.flowIdsLists.forEach(i => {
          if (i.value === obj.value) {
            this.serviceId = i.serviceId
          }
        })
      }
    },
    handleSaveRemark(val) {
      for (const key in val) {
        this.assignUserMap = { [key]: [val[key]] }
      }
      this.handleSubmit('saveWork')
    },
    // 显示评论
    handleShowRemark(validate = true) {
      const _self = this
      this.$refs.formRef
        .handleFormSubmit('formLabels')
        .then(() => {
          this.$refs.generateForm.getData(validate).then((data) => {
            this.formData = data
            getNextNodeInfo({ flowId: this.formDatas.flowId }).then((res) => {
              if (res.length > 0 && res[0].nodeAssignWay !== 'autoAssign') {
                this.$refs.remarkDialogRef.show('选择下级处理人', res)
              } else {
                this.handleSubmit('saveWork')
              }
            })
          })
        })
        .catch(() => {
          _self.$message({
            message: '请完善表单！',
            type: 'error'
          })
        })
    },
    //  提交接口
    handleSubmit(type) {
      const _self = this
      switch (type) {
        case 'saveWork':
          saveWork(
            //  将文件上传attachment放到formData中
            Object.assign(
              {
                formData: JSON.stringify({ ...this.formData, attachment: this.fileInfo }),
                comment: this.comment,
                assignUserMap: this.assignUserMap,
                serviceId: this.serviceId
              },
              this.formDatas
            )
          ).then((res) => {
            _self.$message.success('保存成功')
            this.$router.go(-1)
          })
          break
        case 'saveDraft':
          this.$refs.generateForm.getData(true).then((data) => {
            saveDraft(
              Object.assign(
                {
                  formData: JSON.stringify({ ...data, attachment: this.fileInfo }),
                  comment: this.comment,
                  serviceId: this.serviceId
                },
                this.formDatas
              )
            ).then((res) => {
              _self.$message.success('保存成功，请到草稿箱查看')
              this.$router.go(-1)
            })
          })

          break
        default:
          break
      }
    },
    //  查看流程
    handleFlowView() {
      if (this.formDatas.flowId) {
        this.$router.push({ path: window.prefix + '/bpmn/processDesign/addProcess', query: { type: 'view', flowId: this.formDatas.flowId }})
      }
    },
    // 发生改变
    handleFileUploadProgress(file, fileList) {
      this.fileList = fileList.slice(-3)
    },
    // 文件数量超过3条
    handleExceed(files, fileList) {
      console.log('文件数量超过3条', files)
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    //  上传失败
    handleError(err, file, fileList) {
      console.log('error', err, file, fileList)
    },
    //  上传成功
    handleSuccess(success, file, fileList) {
      // console.log('success', success, file, fileList)
      if (success.code == 200) {
        this.$message.success('上传成功')
        this.fileInfo.push({ ...success.data[0] })
      } else {
        this.$message.error(success.msg)
      }
    },
    //  文件列表取消钩子
    handleRemove(file, fileList) {
      this.fileInfo.forEach((i, index) => {
        if (i[0].file_name == file.response.data[0].file_name) {
          this.fileInfo.splice(index, 1)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-form-item {
  margin: 0 0 20px 0 !important;
}
.container {
  position: relative;
  flex:1;
  overflow:hidden;
  background: #f3f5f6;
  padding: 20px;
  .container-body {
    height: calc(100% - 76px);
    overflow: auto;
  }
  .container-footer {
    background: #fff;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    width: 100%;
    text-align: right;
    padding: 20px;
  }
  .container-list {
    background: #fff;
    border-radius: 4px;
    margin-bottom: 20px;
    padding: 20px;
    .title {
      margin-bottom: 20px;
    }
  }
}

.tips {
  margin-left: 10px;
  border-left: 4px solid #1890ff;
}
</style>
